<template>
	<up-navbar title="幸运集市" :bgColor="bgColor" fixed placeholder leftIconColor="#fff" titleStyle="color:#fff">
		<template #left>
			<view class="u-nav-slot" @click="signIn">
				<image src="@/static/icon/qiandao.png"></image>
				<text class="u-m-l-10 u-p-t-4">{{hasSigned?'已签到':'签到'}}</text>
			</view>
		</template>
	</up-navbar>
	<view v-if="state.luckyInfo">
		<view class="gift-top u-p-30">
			<view class="u-flex u-flex-between u-p-b-20">
				<view class="u-flex u-flex-middle u-font-25 u-text-white">
					<up-icon name="gift-fill" color="#fff" size="22"></up-icon>
					<text class="u-m-l-5 u-font-bold">市集好礼周周送</text>
					<text class="u-text-opacity">｜</text>
					<text class="u-text-opacity">{{state.luckyInfo.fare_type===1?'官方包邮':'付邮领取'}}</text>
				</view>
				<view class="u-btn-dy u-font-24" @click="subscribeMessage">订阅开奖</view>
			</view>
			<view class="u-flex u-flex-middle u-text-white u-font-36 u-p-b-20">
				<view class="u-flex u-flex-middle u-text-white u-font-36">
					<view class="time">
						<text class="time__item">{{ countdown.days }}&nbsp;天&nbsp;</text>
						<text class="time__item">{{ countdown.hours }}&nbsp;时&nbsp;</text>
						<text class="time__item">{{ countdown.minutes }}&nbsp;分&nbsp;</text>
						<text class="time__item">{{ countdown.seconds }}&nbsp;秒</text>
					</view>
				</view>
			</view>
			<view class="gift-cover u-rela">
				<view class="lucky-rules u-abso u-font-26" @click="state.ruleShow=true">抽奖规则</view>
				<image mode="widthFix" :src="state.luckyInfo.cover"></image>
			</view>
			<p class="u-m-t-20 u-m-b-20">{{state.luckyInfo.name}}</p>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>奖品价值：{{state.luckyInfo.price}}元</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>领奖方式：{{state.luckyInfo.fare_type===1?'官方包邮':'付邮领取'}}</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>放号总量：{{state.luckyInfo.total}}个</view>
			</view>
			<view class="u-flex u-flex-between u-m-t-10 u-content-color u-font-26">
				<view>开奖时间：{{state.luckyInfo.end}}</view>
			</view>
		</view>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
		<view class="u-flex u-flex-between u-p-30 u-font-27">
			<text class="u-content-color u-m-t-10">活动发起方</text>
			<view class="u-flex u-flex-middle">
				<up-avatar
					src="https://wx.qlogo.cn/mmhead/Mjzdia7evAzzCUqH2AbqN8XJwySgcV0JIBarHV1gDTfRULXCBFL67kZjkCibGdODEQpG8EtibNJhus/0"
					size="30"></up-avatar>
				<text class="u-m-l-5 u-error-dark">官方发布</text>
			</view>
		</view>
		<block v-if="state.user_nums.length>0">
			<up-gap height="10" bgColor="#fafafa"></up-gap>
			<view class="u-flex u-flex-between u-p-30 u-font-27">
				<text class="u-content-color">我的幸运号({{state.user_nums.length}})</text>
				<view class="u-flex u-flex-between" style="width: 70%;">
					<text></text>
					<view class="lucky-nums u-font-25 u-text-right">
						<block v-for="(item,index) in state.user_nums" :key="index">
							<text v-if="state.luckyInfo.is_end===1" :class="{'u-text-light':item.num!=state.luckyInfo.draw}">{{item.num}}</text>
							<text v-else>{{item.num}}</text>
						</block>
					</view>
				</view>
			</view>
		</block>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
		<view class="u-p-30">
			<view class="u-p-t-40">
				<view class="u-p-l-80 u-p-r-80" v-if="state.isFinish">
					<block v-if="state.isFinish&&state.user_nums.length===0">
						<up-button type="info" text="活动已结束" shape="circle"></up-button>
					</block>
					<!-- <view v-else-if="state.luckyInfo.claim>0">
						<up-button type="error" text="已开奖，查看详情" shape="circle" @click="toDetail(id)"></up-button>
					</view> -->
					<block v-else-if="state.user_nums.length">
						<up-button type="error" disabled text="正在计算开奖，预计2分钟" shape="circle"></up-button>
					</block>
				</view>
				<block v-else-if="state.luckyInfo.single>state.user_nums.length">
					<view class="u-p-l-80 u-p-r-80 u-flex u-flex-between">
						<view style="width: 68%;">
							<up-button type="error" text="开始选号" shape="circle" @click="chooseNum"></up-button>
						</view>
						<view style="width: 30%;">
							<up-button type="success" text="幸运随机" plain shape="circle" @click="randomNum"></up-button>
						</view>
					</view>
					<p class="u-font-25 u-text-center u-p-t-15 u-light-color">
						<text>消耗{{state.luckyInfo.integral}}幸运星/号，已选{{state.user_nums.length}}/{{state.luckyInfo.single}}</text>
					</p>
				</block>
				<block v-else>
					<up-button type="warning" text="达到选号上限，请等待开奖" shape="circle"></up-button>
				</block>
			</view>
			<view v-if="state.user_count>0" class="u-p-t-50">
				<view class="u-font-26 u-text-center u-p-b-10 u-content-color">
					<view>已有{{state.user_count}}人参与，共选{{state.claim||state.luckyInfo.claim}}个幸运号</view>
					<view class="u-flex u-flex-middle u-m-t-20">
						<up-avatar-group :urls="state.urls" size="35" maxCount="15" gap="0.4"></up-avatar-group>
					</view>
				</view>
			</view>
		</view>
		<up-gap height="10" bgColor="#fafafa"></up-gap>
	</view>
	<preview></preview>
	<luckHistory></luckHistory>
	<up-popup :show="state.ruleShow" :round="10" :safe-area-inset-bottom="false" mode="center" :closeable="true"
		@close="state.ruleShow=false">
		<view class="ruleShowBox">
			<p class="u-text-center u-font-30 u-p-30">抽奖规则</p>
			<view class="u-p-l-40 u-p-r-20 u-p-b-40 u-content-color u-font-28">
				<p class="u-error-dark">一、开奖条件：</p>
				<view class="u-m-t-10 u-content-color">
					<p>1.1 活动到达结束时间并且已选号码大于活动最低要求参与号码数量；</p>
					<p>1.2 如果不符合开奖条件，活动到达开奖时间后会返还活动所消耗的积分；</p>
				</view>
				<p class="u-error-dark u-m-t-20">二、开奖规则：</p>
				<view class="u-m-t-10 u-content-color">
					<p>2.1 活动截止后共放出N个幸运号；</p>
					<p class="u-m-t-10">2.2 N个幸运号累加结果为M；</p>
					<p class="u-m-t-10">2.3 所有幸运号累加之和取最后5位所得结果R为中奖参考值；</p>
					<p class="u-m-t-10">2.4 您的幸运号如果等于R或最接近R，即为中奖号码；</p>
					<p class="u-m-t-10">2.5 如果出现差值相同的两个号码，则取较大的号码作为开奖号码；</p>
				</view>
			</view>
		</view>
	</up-popup>
	<up-keyboard mode="number" :dotDisabled="true" confirmText="确认选号" :show="state.keyboardShow"
		:tips="state.currentNum?state.currentNum:state.currentTxt" customStyle="{color:#000}" @change="valChange"
		@backspace="backspace" @confirm="confirm" @cancel="cancel" @close="keyboardHide"></up-keyboard>
	<up-popup :show="state.noCoinShow" overlayOpacity="0.8" bgColor="transparent" :round="10"
		:safe-area-inset-bottom="false" mode="center" :closeable="false" @close="state.noCoinShow=false">
		<view>
			<view class="u-flex u-flex-middle">
				<image src="@/static/icon/star.png" mode="widthFix" style="width:200rpx;height: 200rpx;"></image>
			</view>
			<p class="u-text-center u-font-30 u-m-t-20 u-text-white">啊哦~ 幸运星不足，邀请好友可+<text
					class="u-font-44 u-m-l-4 u-m-r-4">50</text>星/人</p>
			<view class="u-m-t-50">
				<up-button type="success" open-type="share" shape="circle" text="邀请好友"></up-button>
			</view>
		</view>
		<view class="u-flex u-flex-center u-m-t-80 u-p-t-40" @click="state.noCoinShow=false">
			<up-icon name="close-circle" color="#fff" size="40"></up-icon>
		</view>
	</up-popup>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		onUnmounted,
		reactive,
		nextTick,
		computed,
		ref,
		defineEmits,
	} from 'vue';
	import {
		useAuth
	} from '/composables/useAuth';
	import {
		BASE_URL,
		REQUEST_SUCCESS
	} from '/utils/config.js';
	import createApi from '/api/commonAPI.js';
	const commonAPI = createApi(store);
	import {
		useStore
	} from 'vuex';
	const store = useStore();
	const {
		token,
		user_id,
		userInfo,
		hasAuth,
		session_key,
		SET_TOKEN,
		autoLogin,
		setAvatar,
		uploadFile,
		wxLoginByPhone,
		logout,
		refreshAppId,
		hasSigned,
		account,
		notLogin
	} = useAuth();
	// 创建响应式数据
	const bgColor = ref('#f15e69');
	// 定义可以向父组件发送的事件
	const emits = defineEmits(['open-signIn', 'open-login']);
	// 使用 reactive 创建响应式数组  
	const state = reactive({
		ruleShow: false,
		keyboardShow: false,
		currentNum: '',
		currentTxt: '请选择5个幸运数字',
		isFinish: false,
		luckyInfo: null,
		user_count: 0, //已参与人数
		claim: 0, //已选出号码总数
		user_nums: [], //当前用户的选号历史
		urls: [],
		noCoinShow: false,
	})
	// 新增：用于存储倒计时的天、时、分、秒
	const countdown = ref({
		days: '00',
		hours: '00',
		minutes: '00',
		seconds: '00',
	});

	// 新增：定时器
	let timer = null;

	// 倒计时核心方法
	const startCountdown = (endTime) => {
		// 确保之前没有定时器在运行
		if (timer) clearInterval(timer);
		// 将结束时间字符串转换为时间戳，防止多次转换
		const endTimeTimestamp = new Date(endTime).getTime();
		timer = setInterval(() => {
			let totalMilliseconds = Math.max(0, endTimeTimestamp - Date.now());
			if (totalMilliseconds <= 0) {
				clearInterval(timer);
				// 倒计时结束，调用 finish 方法
				finish();
				return;
			}
			const totalSeconds = Math.floor(totalMilliseconds / 1000);
			const days = Math.floor(totalSeconds / (60 * 60 * 24));
			const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60));
			const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
			const seconds = totalSeconds % 60;
			const formatNumber = (num) => String(num).padStart(2, '0');
			// 更新响应式数据
			countdown.value = {
				days: formatNumber(days),
				hours: formatNumber(hours),
				minutes: formatNumber(minutes),
				seconds: formatNumber(seconds)
			};
		}, 1000);
	};
	onMounted(async () => {
		uni.showLoading({
			title: '加载中...'
		})
		await getLuckyCurrent()
		if (token.value && state.luckyInfo) {
			getAllData()
		}
	});
	onUnmounted(() => {
		// 组件卸载时，清理定时器，防止内存泄漏
		if (timer) {
			clearInterval(timer);
		}
	});
	function getAllData(){
		getLuckyUserCount()
		getLuckyCurUserNums()
		getLuckyAvatar()
		getLuckyAllNums()
	}
	function convertToCountdownTime(endTimeStr) {
		// 1. 将时间字符串转换为 Date 对象
		const endTime = new Date(endTimeStr);
		// 2. 获取当前时间的毫秒数
		const now = Date.now(); // 相当于 new Date().getTime()
		// 3. 计算时间差（以毫秒为单位）
		const timeDifference = endTime.getTime() - now;
		// 4. 确保返回的值非负
		return Math.max(0, timeDifference);
	}
	//获取当前幸运购 
	async function getLuckyCurrent() {
		await commonAPI.lastCurrent().then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.luckyInfo = res.data
				startCountdown(state.luckyInfo.end)
				const luckyShareInfo =
					uni.setStorageSync('luckyShareInfo', {
						cover: state.luckyInfo.cover,
						name: state.luckyInfo.name,
						id: state.luckyInfo.id
					})
				uni.hideLoading()
			} else {
				uni.showToast({
					icon: 'none',
					title: '当前暂无可参与抽奖'
				})
				uni.hideLoading()
			}
		})
	}
	// 定义 finish 方法  
	const finish = (e) => {
		//倒计时结束，调取接口获取开奖状态和结果
		// getLuckyCurrent()
		state.isFinish = true
	};

	function signIn() {
		// 触发 'open-signIn' 事件
		emits('open-signIn');
	}

	function chooseNum() {
		if (!userInfo.value.nick_name && !userInfo.value.avatar) {
			emits('open-login');
			return false;
		}
		//这里先要判断他的积分是否可以满足单次选号所需
		if (account.value.integral < state.luckyInfo.integral) {
			state.noCoinShow = true
			return false;
		}
		state.keyboardShow = true
	}
	const valChange = (val) => {
		if (state.currentNum.length > 4) {
			uni.showToast({
				icon: 'none',
				title: '只能选择5个数字哦'
			})
			return false;
		}
		state.currentNum += val;
		// **限制不能以0开头**
		if (parseInt(state.currentNum) < 1) {
			uni.showToast({
				icon: 'error',
				title: '不能以0开头'
			});
			state.currentNum = ''
		}
	};

	const backspace = () => {
		// 删除value的最后一个字符
		if (state.currentNum.length) {
			state.currentNum = state.currentNum.substr(0, state.currentNum.length - 1);
		}
	};
	const keyboardHide = () => {
		state.keyboardShow = false
		state.currentNum = ''
	}
	//随机选号
	const randomNum = () => {
		if (!userInfo.value.nick_name && !userInfo.value.avatar) {
			emits('open-login');
			return false;
		}
		//这里先要判断他的积分是否可以满足单次选号所需
		if (account.value.integral < state.luckyInfo.integral) {
			state.noCoinShow = true
			return false;
		}
		state.keyboardShow = true
		let randomNumbers = [];
		// 生成第一个数字，范围在 1-9
		randomNumbers.push(Math.floor(Math.random() * 9) + 1);
		// 生成接下来的4个数字，范围在 0-9
		for (let i = 0; i < 4; i++) {
			randomNumbers.push(Math.floor(Math.random() * 10));
		}
		state.currentNum = randomNumbers.join('');
	}
	//取消选号
	const cancel = () => {
		state.keyboardShow = false
		uni.showToast({
			icon: 'none',
			title: '取消选号'
		})
		state.currentNum = ''
	}
	//确认选号
	const confirm = () => {
		if (state.currentNum.length < 5 || state.currentNum.length > 5) {
			uni.showToast({
				icon: 'none',
				title: '请选择5个数字哦'
			})
			return false;
		}
		state.keyboardShow = false
		//请求提交选号的接口，判断号码是否可选
		commonAPI.luckyBuy(state.luckyInfo.id, {
			nums: state.currentNum
		}).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				if (res.data.has_buy_nums[0] === state.currentNum) {
					uni.showToast({
						icon: 'error',
						title: '该号码已被选'
					})
					return false;
				}
				if (res.data.can_buy_nums[0] === state.currentNum) {
					uni.showToast({
						icon: 'success',
						title: '选号成功'
					})
					getLuckyAvatar()
					state.user_count = res.data.user_count
					state.claim = res.data.claim
					state.user_nums = res.data.user_nums
					state.currentNum = ''
				}
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
				state.currentNum = ''
			}
		})
	}
	//当前活动已参与人数 lucky_user_count
	function getLuckyUserCount() {
		commonAPI.lucky_user_count(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.user_count = res.data
			}
		})
	}
	//获取当前参与人数
	function getLuckyAllNums() {
		commonAPI.lucky_user_nums(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.all_join_nums_count = res.data.length
			}
		})
	}
	//获取当前参与人头像 lucky_avatar
	function getLuckyAvatar() {
		state.urls = []
		commonAPI.lucky_avatar(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				res.data.forEach(item => {
					state.urls.push(item.user_avatar)
				})
			}
		})
	}
	//获取当前参与在当前活动中的选号 lucky_cur_user_nums
	function getLuckyCurUserNums() {
		commonAPI.lucky_cur_user_nums(state.luckyInfo.id).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				state.user_nums = res.data
			}
		})
	}
	//是否订阅了
	async function subscribeMessage() {
		const templateId = '9DmL-aSZFeLNSuM7egkNoLdRRCqx7sIB2jPcFuY3qU4'; // 替换为你的模板 ID
		try {
			const res = await uni.requestSubscribeMessage({
				tmplIds: [templateId]
			});
			if (res[templateId] === 'accept') {
				uni.showToast({
					title: '订阅成功'
				});
			} else if (res[templateId] === 'reject') {
				uni.showToast({
					title: '您拒绝了订阅消息，将无法收到通知',
					icon: 'none',
					duration: 1000
				});
			} else if (res[templateId] === 'ban') {
				uni.showToast({
					title: '您已关闭订阅',
					icon: 'none'
				});
			}
		} catch (err) {
			console.error('订阅失败:', err);
			uni.showToast({
				title: '订阅失败，请稍后再试',
				icon: 'none'
			});
		}
	}
</script>

<style lang="scss" scoped>
	.u-nav-slot {
		border: 1px solid rgba(255, 255, 255, .2);
		border-radius: 30rpx;
		padding: 4px 20rpx;
		color: #fff;
		font-size: 26rpx;
		background-color: rgba(255, 255, 255, .1);
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 34rpx;
			height: 34rpx;
			display: block;
		}
	}
</style>